<!-- 一键解隔离工单 -->
<script setup lang="ts">
import { getCurrentInstance, onMounted, computed, ref } from "vue";
import { detail, detailCount, oneTouchHandle, commitTask, handGms, queryForUpdateAfter, disisolationCheck } from "@/api/erc/detector";
import EditDropDownLight from "@/views/all/equip/components/EditDropDownLight.vue";
import BaseInfo from "./components/BaseInfo.vue";
import LogInfo from "./components/LogInfo.vue";
import IconWarningPng from "@/assets/images/erc/icon_warning.png";
import { STATUS_CONFIG, GL_CODES, JGL_CODES, gltableColumns, jgltableColumns, tagColorList, tagBgColorList, tagBorderColorList } from "./const";
import { PxMessage, PxMessageBox } from "px-ui";
const props = defineProps(["currentData", "source"]);
const pageName = defineModel();
const data = ref<any>({});
const resultData = ref<any>();
const isGL = computed(() => GL_CODES.includes(data.value?.taskStatusKey));
const isJGL = computed(() => JGL_CODES.includes(data.value?.taskStatusKey));
const tableColumns = computed(() => {
  if (isGL.value) {
    return gltableColumns;
  }
  return jgltableColumns;
});
const init = async () => {
  const { id } = props?.currentData;
  const res = await detail({ id });
  data.value = res;
  const params = {
    taskId: res.id,
    taskType: GL_CODES.includes(res?.taskStatusKey) ? "ISOLATION" : "DISISOLATION"
  };
  const countData = await detailCount(params);
  resultData.value = countData;
};
onMounted(() => {
  init();
});
const executeRemark = ref("");
// 返回上一页
const handleBack = () => {
  const action = isGL.value ? "隔离" : "解隔离";
  if (resultData.value?.totalCount !== resultData.value?.successCount) {
    PxMessageBox.confirm(`您还有未${action}侦测器，请注意！`, "提示", {
      confirmButtonText: "确定退出",
      cancelButtonText: "取消",
      confirmButtonClass: "px-button--danger",
      type: "warning"
    }).then(async () => {
      executeRemark.value = "";
      pageName.value = props.source;
    });
  } else {
    executeRemark.value = "";
    pageName.value = props.source;
  }
};
// 提交
const handleSubmit = async () => {
  if (resultData.value.totalCount !== resultData.value.successCount && !executeRemark) {
    // 1、未全部隔离/解隔离
    if (isGL.value) {
      return PxMessage.warning("侦测器未全部隔离成功，请填写备注！");
    } else {
      return PxMessage.warning("侦测器未全部解隔离成功，请填写备注！");
    }
  } else {
    // 2、提交
    PxMessageBox.confirm(`确认提交工单吗？`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      await commitTask({
        taskId: data.value.id,
        taskType: isGL.value ? "ISOLATION" : "DISISOLATION",
        executeRemark: executeRemark.value
      });
      PxMessage.success("提交成功");
      pageName.value = "list";
    });
  }
};
// 禁用
const handleDisabled = row => {
  if (isGL.value) {
    return row.isolateResult === 1;
  } else {
    return row.disisolateResult === 1;
  }
};
const dialogVisible = ref(false);
const percentage = ref(0);
const updateStatus = ref(false);
const getResult = taskType => {
  // 进度条动画
  percentage.value = 0;
  updateStatus.value = false;
  dialogVisible.value = true;
  const timer = setInterval(() => {
    if (percentage.value < 99 && !updateStatus.value) {
      percentage.value += 1;
    } else if (!updateStatus.value) {
      percentage.value = 99;
    } else {
      percentage.value = 100;
      dialogVisible.value = false;
    }
  }, 150);
  // 隔离结果查询
  queryForUpdateAfter({
    taskId: data.value.id,
    taskType
  })
    .then(() => {
      init();
    })
    .finally(() => {
      updateStatus.value = true;
      dialogVisible.value = false;
      clearInterval(timer);
    });
};
const isolateInOthers = ref({}); //在其它隔离工单存在的侦测器
const isolateInOthersVisible = ref(false);
// 一键隔离解隔离
const oneTouch = async taskType => {
  const action = isGL.value ? "隔离" : "解隔离";
  // 1、隔离解隔离提示
  PxMessageBox.confirm(`是否确认对侦测器进行${action}操作？请严格按照SOP验证流程确认`, "提示", {
    confirmButtonText: `执行${action}`,
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  }).then(async () => {
    if (taskType === "DISISOLATION") {
      const res = await disisolationCheck({ taskId: data.value.id, taskType });
      if (Object.keys(res).length) {
        isolateInOthers.value = res;
        isolateInOthersVisible.value = true;
        return;
      } else {
        isolateInOthers.value = {};
      }
    }
    submitOneTouch(taskType);
  });
};
const submitOneTouch = async (taskType, jump?: boolean) => {
  if (jump) {
    isolateInOthersVisible.value = false;
  }
  // 一键隔离解隔离
  await oneTouchHandle({
    taskId: data.value.id,
    taskType,
    jump
  });
  getResult(taskType);
};
// 手动GMS隔离/解隔离
const handleGMS = async row => {
  if (isGL.value) {
    PxMessageBox.confirm(`确定要强制修改“${row.detectorCode}”的状态为隔离吗？`, "提示", {
      confirmButtonText: `强制隔离`,
      cancelButtonText: "取消",
      confirmButtonClass: "px-button--danger",
      type: "warning"
    }).then(async () => {
      await handGms({
        id: row.id,
        taskType: isGL.value ? "ISOLATION" : "DISISOLATION"
      });
      init();
    });
  } else {
    const HTML = `<div>
      <div style="margin-bottom:8px;display:flex;">
      <img src="${IconWarningPng}" style="width:20px;height:20px;margin-top:2px;margin-right:8px;">
      请确认是否在GMS系统手动解隔离成功！请严格按照SOP确认！
      </div>
      <ul style="
      padding: 12px 16px;
      background: #f7f7f7;
      border-radius: 4px;
      line-height: 22px;
      color: rgba(0,0,0,0.8);
      ">
      <li style="margin-bottom:2px;display:flex;"><div>设备位号：</div><div>${row.detectorCode || "-"}</div></li>
      <li style="margin-bottom:2px;display:flex;"><div>气体类型：</div><div>${row.gasName || "-"}</div></li>
      <li style="margin-bottom:2px;display:flex;"><div>位置：</div><div>${row.location || "-"}</div></li>
      <li style="display:flex;"><div>当前状态：</div>
      <div>${row.disisolateAfterStatus || row.disisolateBeforeTime || "-"}</div></li>
      </ul></div>`;
    PxMessageBox.confirm(HTML, "GMS解隔离确认", {
      confirmButtonText: `强制解隔离`,
      cancelButtonText: "取消",
      confirmButtonClass: "px-button--danger",
      dangerouslyUseHTMLString: true
    }).then(async () => {
      await handGms({
        id: row.id,
        taskType: isGL.value ? "ISOLATION" : "DISISOLATION"
      });
      init();
    });
  }
};
const getHandleType = type => {
  if (type === "AUTO") {
    return "自动";
  }
  if (type === "HAND") {
    return "手动";
  }
  return "-";
};
const getStatus = val => {
  if (val === "true") {
    return "隔离";
  }
  if (val === "false") {
    return "未隔离";
  }
  return val || "-";
};
const logVisible = ref(false);
const logData = ref();
const handleDownload = row => {
  logData.value = row;
  logVisible.value = true;
  // const params = {
  //   id: row.id,
  //   fileName: row.fileName
  // };
  // proxy.download("post", "/sharing/api/v1/file/download", params, row.originalName);
};
</script>
<template>
  <div class="view-equip-detail view-detail">
    <div class="view-detail-header">
      <div class="view-title">
        <px-button type="primary" icon="ArrowLeft" @click="handleBack">返回</px-button>
        <div class="title">隔离工单详情</div>
        <p
          class="status"
          :style="{
            color: `${tagColorList[data.taskStatusKeyDesc]}`,
            border: `1px solid ${tagBorderColorList[data.taskStatusKeyDesc]}`,
            backgroundColor: `${tagBgColorList[data.taskStatusKeyDesc]}`
          }"
        >
          <span>{{ data.taskStatusKeyDesc }}</span>
        </p>
      </div>
    </div>
    <px-scrollbar class="view-detail-body">
      <div>
        <BaseInfo :data="data" />
        <EditDropDownLight dropdownTitle="侦测器隔离清单">
          <template v-slot:content>
            <div class="table-box">
              <div class="mb-[8px]">
                <div class="table-header">
                  <div>
                    <px-button v-if="isGL" v-has="'ERC_CALENDAR_DETECTOR_TODO_BTN'" type="primary" @click="oneTouch('ISOLATION')">一键隔离</px-button>
                    <px-button v-if="isJGL" v-has="'ERC_CALENDAR_DETECTOR_CANCEL_BTN'" type="primary" @click="oneTouch('DISISOLATION')"
                      >一键解隔离</px-button
                    >
                  </div>
                  <div v-if="resultData">
                    <div v-if="isGL">
                      <span>
                        应隔离侦测器：<span class="primary">{{ resultData?.totalCount }}</span
                        >颗</span
                      >
                      <span>
                        成功隔离：<span class="success">{{ resultData?.successCount }}</span
                        >颗</span
                      >
                      <span>
                        失败隔离：<span class="error">{{ resultData?.failCount }}</span
                        >颗</span
                      >
                    </div>
                    <div v-if="isJGL" class="actionInfo">
                      <span>
                        应解隔离侦测器：<span class="primary">{{ resultData?.totalCount }}</span
                        >颗</span
                      >
                      <span>
                        成功解隔离：<span class="success">{{ resultData?.successCount }}</span
                        >颗</span
                      >
                      <span>
                        失败解隔离：<span class="error">{{ resultData?.failCount }}</span
                        >颗</span
                      >
                    </div>
                  </div>
                </div>
              </div>
              <px-table
                :data="data?.detectorChecklistDTOList || []"
                :max-height="data?.detectorChecklistDTOList?.length ? '395px' : undefined"
                class="equip-table"
                size="small"
                border
              >
                <px-table-column label="序号" type="index" width="55" align="center" fixed="left" />
                <px-table-column
                  v-for="(item, index) in tableColumns"
                  :label="item.label"
                  :min-width="item.minWidth"
                  :show-overflow-tooltip="item.showOverflowTooltip"
                  :fixed="item.fixed"
                  :key="index"
                  ><template #default="scope" v-if="item.prop === 'isolateFileDTO'">
                    <px-button
                      v-if="scope.row['isolateFileDTO']"
                      v-has="'ERC_CALENDAR_DETECTOR_DOWNLOAD_FILE'"
                      link
                      type="primary"
                      @click="handleDownload(scope.row['isolateFileDTO'])"
                      >下载日志</px-button
                    >
                    <span v-else>-</span>
                  </template>
                  <template #default="scope" v-else-if="item.prop === 'disisolateFileDTO'">
                    <px-button
                      v-if="scope.row['disisolateFileDTO']"
                      v-has="'ERC_CALENDAR_DETECTOR_DOWNLOAD_FILE'"
                      link
                      type="primary"
                      @click="handleDownload(scope.row['disisolateFileDTO'])"
                      >下载日志</px-button
                    >
                    <span v-else>-</span>
                  </template>
                  <template #default="scope" v-else-if="item.prop === 'isolateType' || item.prop === 'disisolateType'">{{
                    getHandleType(scope.row[item.prop])
                  }}</template>
                  <template #default="scope" v-else-if="['isolateBeforeStatus', 'isolateAfterStatus'].includes(item.prop)">
                    <px-tag v-if="scope.row[item.prop] === 'true'" type="success" class="mx-1" effect="dark"> 隔离 </px-tag>
                    <px-tag v-else class="mx-1" type="danger" effect="dark"> 未隔离 </px-tag>
                  </template>
                  <template #default="scope" v-else-if="['disisolateBeforeStatus', 'disisolateAfterStatus'].includes(item.prop)">
                    <px-tag v-if="scope.row[item.prop] === 'true'" type="danger" class="mx-1" effect="dark"> 隔离 </px-tag>
                    <px-tag v-else class="mx-1" type="success" effect="dark"> 未隔离 </px-tag>
                  </template>
                  <template #default="scope" v-else>{{
                    scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
                  }}</template>
                </px-table-column>
                <px-table-column fixed="right" label="操作" min-width="160" align="center">
                  <template #default="scope">
                    <px-button :disabled="handleDisabled(scope.row)" class="button" type="primary" @click="handleGMS(scope.row)">{{
                      isGL ? "手动GMS隔离" : "手动GMS解隔离"
                    }}</px-button>
                  </template>
                </px-table-column>
              </px-table>
            </div>
          </template>
        </EditDropDownLight>
        <EditDropDownLight :dropdownTitle="isGL ? '侦测器隔离备注' : '侦测器解隔离备注'">
          <template v-slot:content>
            <px-input v-model="executeRemark" :rows="4" type="textarea" :placeholder="isGL ? '请输入侦测器隔离备注' : '请输入侦测器解隔离备注'" />
          </template>
        </EditDropDownLight>
      </div>
    </px-scrollbar>
    <!-- 一键隔离解隔离进度 -->
    <px-dialog v-model="dialogVisible" title="" width="30%" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <px-progress :text-inside="true" :stroke-width="26" :percentage="percentage" />
      <div class="warningInfo">{{ isGL ? "隔离进行中，请勿离开..." : "解隔离进行中，请勿离开..." }}</div>
    </px-dialog>
    <!-- 在其它工单隔离的侦测器列表 -->
    <px-dialog v-model="isolateInOthersVisible" title="" width="40%">
      <ul>
        <li class="row-info" v-for="item in Object.keys(isolateInOthers)" :key="item">
          <px-tooltip :content="`侦测器${item}于工单${isolateInOthers[item]}已隔离`">
            <px-text truncated style="font-size: 14px">
              侦测器<span class="row-info-name">{{ item }}</span
              >于工单<span class="row-info-name">{{ isolateInOthers[item] }}</span
              >已隔离
            </px-text>
          </px-tooltip>
        </li>
      </ul>
      <div class="dialog-footer">
        <px-button type="warning" @click="submitOneTouch('DISISOLATION', true)">跳过上述隔离工单中的侦测器，仅解隔离其它侦测器</px-button>
        <px-button type="danger" @click="isolateInOthersVisible = false">取消</px-button>
      </div>
    </px-dialog>

    <LogInfo v-if="logVisible" v-model="logVisible" :data="logData" />
    <div class="info-form-btns"><px-button @click="handleBack">取消</px-button><px-button type="primary" @click="handleSubmit">提交</px-button></div>
  </div>
</template>
<style lang="scss" scoped>
@import url("@/views/erc/scss/view-detail.scss");
.warningInfo {
  color: #333;
  text-align: center;
  margin-top: 8px;
}
.row-info {
  color: #333;
  line-height: 18px;
}
.row-info-name {
  font-weight: bold;
}
.dialog-footer {
  margin-top: 16px;
  text-align: right;
}
.view-detail {
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
  height: calc(100vh - 190px);
  .view-detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 14px;
  }
  .view-title {
    display: flex;
    align-items: center;
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .actionInfo {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.8);
      line-height: 22px;
    }
  }
  .primary {
    font-size: 16px;
    font-weight: 600;
    color: #3b82f6;
    line-height: 22px;
    margin-right: 2px;
  }
  .success {
    font-size: 16px;
    font-weight: 600;
    color: #10b981;
    line-height: 22px;
    margin-right: 2px;
  }
  .error {
    font-size: 16px;
    font-weight: 600;
    color: #ef4444;
    line-height: 22px;
    margin-right: 2px;
  }
  .title {
    font-size: 20px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.9);
    line-height: 32px;
    margin-left: 16px;
  }
  .status {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
  .point {
    border-radius: 50%;
    height: 10px;
    width: 10px;
    margin-right: 6px;
  }
  .table-box {
    position: relative;
  }
  .remark {
    font-size: 14px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.8);
    line-height: 22px;
    margin-top: 8px;
  }
  .info-form-btns {
    position: fixed;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 64px;
    padding-right: 24px;
    background: #fff;
    box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
  }
}
.status {
  box-sizing: border-box;
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 22px;
  padding: 3px 10px;
  font-size: 12px;
  line-height: 22px;
  border-radius: 4px;
}
.view-detail-body {
  height: calc(100vh - 268px);
}
</style>
